package com.raulraja.util.upload;

import com.raulraja.util.thumbnails.ThumbnailGeneratorEngine;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * File upload service to demonstrate files uploads and handing over the files to the thumbnail generation system
 */
public class FileUploadService extends SimpleFormController {

	private final static Logger log = Logger.getLogger(FileUploadService.class);

	private ThumbnailGeneratorEngine thumbnailGeneratorEngine;

	public void setThumbnailGeneratorEngine(ThumbnailGeneratorEngine thumbnailGeneratorEngine) {
		this.thumbnailGeneratorEngine = thumbnailGeneratorEngine;
	}

	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		FileUpload fileUpload = (FileUpload) command;
		MultipartFile file = fileUpload.getFile();
		InputStream stream = file.getInputStream();
		try {
			//generate thumbnails
			thumbnailGeneratorEngine.generateThumbnails(file.getName(), stream, file.getContentType());
		} catch (Exception e) {
			log.error(e);
		} finally {
			stream.close();
		}
		return super.onSubmit(request, response, command, errors);
	}

	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
			throws ServletException {
		// to actually be able to convert Multipart instance to byte[]
		// we have to register a custom editor
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
		// now Spring knows how to handle multipart object and convert them
	}

}